import { resetRouter } from '@/router'
import { constantRouterMap } from '@/config/router.config'
import { PERMISSION_MODULE } from '@/store/mutation-types'
import Vue from 'vue'

export function filterModuleChildRouters (routers, module) {
  if (module === '-1') return routers

  const menus = routers[0].children
  routers[0].children = menus.find(menu => {
    return menu.name === module
  }).children

  return routers
}

const permission = {
  state: {
    routers: constantRouterMap,
    permissionModule: '-1', // 模块类型 -1 表示所有模块
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, data) => {
      state.addRouters = data
      state.routers = constantRouterMap.concat(data)
    },
    SET_PERMISSION_MODULE: (state, data) => {
      state.permissionModule = data
    }
  },
  actions: {
    // 动态添加主界面路由
    ResetAppRouter ({ commit, state }, routes) {
      return new Promise(resolve => {
        let routelist = routes.constRoutes
        resetRouter()
        commit('SET_ROUTERS', routelist)
        resolve()
      })
    },
    // 动态添加主界面路由
    UpdateAppRouter ({ commit, state }, routes) {
      return new Promise(resolve => {
        let routelist = routes.constRoutes
        commit('SET_ROUTERS', routelist)
        resolve()
      })
    },
    SetPermissionModule ({ commit, state }, module) {
      commit('SET_PERMISSION_MODULE', module || '-1')
      Vue.ls.set(PERMISSION_MODULE, module || '-1')
    }
  }
}

export default permission
